# returnsBoxplot
# returnsHistogram
# returnsMeanPlot
# returnsLinePlot


returnsBoxplot <- function (returns, main="") {
  par(mfrow=c(1,1))
  boxplot(as.matrix(returns)*100, notch=TRUE, main=main, 
    xlab=paste("n Tage nach Auftreten des Musters '", main, "'", sep=""), ylab="Rendite [%]")
  abline(h=0)
}

allreturnsBoxplot <- function(returnslist) {
  for (i in 1:length(returnslist)) {
    returnsBoxplot(returnslist[[i]], main=names(returnslist)[i])
  }
}

returnsHistogram <- function (returns, title="") {
  if (dim(returns)[2] > 1) {
    columns <- dim(returns)[2] / 2
    par(mfrow=c(2,columns))
  }
  for (i in 1:dim(returns)[2]) {
    hist(returns[,i], main=paste(title,'t +',i, sep=' '), xlab='', breaks=30, col='blue', prob=TRUE)
    lines(density(returns[,i]), col='red', lwd=2)
  }
}

returnsMeanPlot <- function(returns, main="") {
  colavg <- colMeans(returns, na.rm=TRUE)*100
  colsd <- colSd(returns, na.rm=TRUE)*100
  ylim1 <- min(-3, min(colavg))
  ylim2 <- max(3, max(colavg))
  if (min(colavg)> -0.5) {
    ylim1=0
  }
  if (max(colavg)< 0.5) {
    ylim2=0
  }
  par(mar=c(5,4,4,5)+.1)
  plot(colavg, type="l", col="red", lwd=3, main=main, 
       xlab=paste("n Tage nach Auftreten des Musters '", main, "'", sep=""), ylab="", ylim=c(ylim1,ylim2))
  mtext("Arithm. Mittel der Renditen [%]", side=2, line=3, col="red")
  par(new=TRUE)
  plot(colsd, type="l", col="blue", lwd=3, xaxt="n", xlab="", ylab="", yaxt="n", ylim=c(0,10))
  axis(4)
  mtext("Standardabweichung", side=4, line=3, col="blue")
  legend("top",col=c("red","blue"),lty=1, lwd=3, legend=c("Rendite","Standardabw."))
}

# example :
# gr <- getCSPGroupReturn("METALS", n=20)
# allreturnsMeanPlot(gr)
allreturnsMeanPlot <- function(returnslist) {
  for (i in 1:length(returnslist)) {
    returnsMeanPlot(returnslist[[i]], main=names(returnslist)[i])
  }  
}

returnsLinePlot <- function(returns) {
  if('package:reshape' %in% search() || require('reshape',quietly=TRUE)) {}
  if('package:ggplot2' %in% search() || require('ggplot2',quietly=TRUE)) {}  
  
  molten <- melt(t(as.data.frame(returns)))
  colnames(molten) <- c('period', 'date', 'return')
  ggplot(molten, aes(period, return)) + geom_line(aes(colour=date))
}